<template>
  <div class="app-container">
    <div v-if="isSearchBtn" class="filter-container">
      <el-input v-model="listQuery.title" placeholder="昵称|openid" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.is_black" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>

    </div>
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <div style="margin-bottom: 0.625rem;height: 2.5rem;">
        <el-button v-show="isShowBtn" v-permission="'wechatuser@black'" class="filter-item" type="danger" icon="el-icon-circle-close" @click="handleDeleteAll">
          批量拉黑/取消拉黑
        </el-button>
        <el-button circle style="float: right;" :loading="loadingSync" icon="el-icon-magic-stick" @click="syncData" />
        <el-button circle style="float: right;" icon="el-icon-search" @click="showBtn" />
        <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{background:'#eee',color:'#606266'}"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @select-all="showDeleteBtn"
        @select="showDeleteSelectBtn"
      >
        <el-table-column
          align="center"
          type="selection"
        />
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" align="center">
          <template slot-scope="{row}">
            <span>{{ row.nickname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="微信号" align="center" width="180">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleUpdate(row)">{{ row.openid }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否关注" align="center">
          <template slot-scope="{row}">
            <el-tag v-if="row.subscribe===1" effect="dark" type="success">已关注</el-tag>
            <el-tag v-if="row.subscribe===0" effect="dark" type="danger">未关注</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关注时间" width="160">
          <template slot-scope="{row}">
            <span>{{ row.subscribe_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="{row}">
            <span>{{ row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否拉黑" align="center">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_black===1" effect="dark" type="danger">已拉黑</el-tag>
            <el-tag v-if="row.is_black===0" effect="dark" type="success">未拉黑</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="同步时间" width="160">
          <template slot-scope="{row}">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button v-permission="'wechatuser@remark'" title="设置备注" icon="el-icon-edit" circle type="primary" @click="handleUpdate(row)" />
            <el-button v-if="row.is_black===0" v-permission="'wechatuser@black'" title="拉黑" icon="el-icon-circle-close" circle type="danger" @click="handleDelete(row,$index)" />
            <el-button v-if="row.is_black===1" v-permission="'wechatuser@black'" title="取消拉黑" icon="el-icon-circle-check" circle type="success" @click="handleDelete(row,$index)" />
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.p" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog title="设置备注" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
        <div class="el-col el-col-24">
          <el-form-item label="昵称" prop="nickname">
            <span>{{ temp.nickname }}</span>
          </el-form-item>
        </div>
        <div class="el-col el-col-24">
          <el-form-item label="openId" prop="openid">
            <span>{{ temp.openid }}</span>
          </el-form-item>
        </div>
        <div class="el-col el-col-24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="temp.remark" placeholder="请输入remark" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, syncData, updateMark, black } from '@/api/wechat'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: '0', display_name: '未拉黑' },
  { key: '1', display_name: '已拉黑' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PagePermission',
  components: { Pagination },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      cascaderData: [],
      loadingSync: false,
      isSearchBtn: false,
      listQuery: {
        p: 1,
        limit: 10,
        title: undefined,
        is_black: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      statusOptions: ['未拉黑', '已拉黑'],
      temp: {
        id: undefined,
        openid: '',
        remark: '',
        nickname: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        remark: [{ required: true, message: '备注必填', trigger: 'change' }]
      },
      isShowSwitch: '',
      ids: [],
      isShowBtn: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    syncData() {
      this.loadingSync = true
      syncData().then(response => {
        this.loadingSync = false
        this.getList()
        this.$message({
          message: response.message,
          type: 'success'
        })
      })
    },
    showBtn() {
      this.isSearchBtn = this.isSearchBtn === false
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    showDeleteBtn: function(selection) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    showDeleteSelectBtn: function(selection, row) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    handleDeleteAll() {
      this.$confirm('此操作将拉黑/取消拉黑该粉丝, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {}
        data.ids = this.ids
        this.listLoading = true
        black(data).then(response => {
          this.ids = []
          this.getList()
          this.isShowBtn = false
          this.listLoading = false
          this.$message({
            message: response.message,
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    handleFilter() {
      this.listQuery.p = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetQuery() {
      this.listQuery = {
        p: 1,
        limit: 10,
        title: undefined,
        is_black: undefined,
        sort: '+id'
      }
      this.getList()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateMark(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '设置成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      const tempData = {}
      tempData.ids = row.id
      this.$confirm('此操作将拉黑/取消拉黑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        black(tempData).then(() => {
          this.dialogFormVisible = false
          this.list[index].is_black = row.is_black === 1 ? 0 : 1
          this.$notify({
            title: 'Success',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style>
  .filter-item{
    margin-right: 0.3125rem;
  }
</style>
